package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.entity.com.PersonnelUse;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.PersonnelUseService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/17.
 */
@Controller
@RequestMapping(value = "/com/personnelUse")
public class PersonnelUseController extends BaseController {
    private static final long serialVersionUID = 430391299131228268L;

    @Autowired
    private PersonnelUseService personnelUseService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DutyService dutyService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            PersonnelUse personnelUse=personnelUseService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("personnelUse", personnelUse);
        }
        model.addAttribute("parentId", parentId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelUse_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            PersonnelUse personnelUse=personnelUseService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("personnelUse", personnelUse);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelUse_read";
    }

    /**
     * 保存Model数据
     */
    private PersonnelUse saveModel(User user, String keyId, String nature, Double salary,String contractDateStart,
                                   String contractDateEnd, String trialDateStart, String trialDateEnd, String parentId) throws ParseException {

        PersonnelUse personnelUse = null;
        if(StringUtils.isBlank(keyId)){
            personnelUse=new PersonnelUse();
            personnelUse.setCreater(user);
            personnelUse.setCompany(user.getCompany());
        }else{
            personnelUse=personnelUseService.get(keyId);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(nature)){
            personnelUse.setNature(Integer.parseInt(nature));
        }
        if(salary!=null){
            personnelUse.setSalary(salary);
        }
        if(StringUtils.isNotEmpty(contractDateStart)){
            personnelUse.setContractDateStart(sdf.parse(contractDateStart));
        }
        if(StringUtils.isNotEmpty(contractDateEnd)){
            personnelUse.setContractDateEnd(sdf.parse(contractDateEnd));
        }
        if(StringUtils.isNotEmpty(trialDateStart)){
            personnelUse.setTrialDateStart(sdf.parse(trialDateStart));
        }
        if(StringUtils.isNotEmpty(trialDateEnd)){
            personnelUse.setTrialDateEnd(sdf.parse(trialDateEnd));
        }
        if(StringUtils.isNotEmpty(parentId)){
            personnelUse.setPersonnelInfo(personnelInfoService.get(parentId));
            personnelUse.setPersonnelInfoId(parentId);
            personnelUse.setUserId(personnelInfoService.get(parentId).getUser().getId());
        }
        personnelUse.setName("名字居然不能为空");

        String personnelUserString="";
        Set<Duty> dutySet=personnelInfoService.get(parentId).getUser().getDutySet();
        for(Duty duty:dutySet){
            Department department=duty.getPower().getDepartment().getParent()==null?duty.getPower().getDepartment():duty.getPower().getDepartment().getParent();
            for(Department dept:department.getChildren()){
                Set<Power> powerSet=dept.getPowerSet();
                for(Power power:powerSet){
                    if(power.getPost().getName().equals("人事专员")){
                        List<User> usersList=dutyService.getPersons(dept,power.getPost());
                        for(User user1:usersList){
                            personnelUserString+=user1.getId()+",";
                        }
                    }
                }
            }
        }
        personnelUse.setPersonnelUserString(personnelUserString);
        personnelUse.setUserId(personnelInfoService.get(parentId).getUser().getId());
        personnelUse.setPersonnelInfoId(parentId);


        return personnelUse;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String nature,
                       Double salary,
                       String contractDateStart,
                       String contractDateEnd,
                       String trialDateStart,
                       String trialDateEnd,
                       String parentId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelUse personnelUse = saveModel(user, keyId, nature, salary, contractDateStart, contractDateEnd, trialDateStart, trialDateEnd, parentId);

        if(StringUtils.isNotEmpty(keyId)){
            personnelUseService.update(personnelUse);
            rMap.put("message", "更新成功");
        } else {
            personnelUseService.save(personnelUse, "com.fz.us.oa.core.entity.com.PersonnelUse");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String nature,
                         Double salary,
                         String contractDateStart,
                         String contractDateEnd,
                         String trialDateStart,
                         String trialDateEnd,
                         String parentId,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        PersonnelUse personnelUse = saveModel(user, keyId, nature, salary, contractDateStart, contractDateEnd, trialDateStart, trialDateEnd, parentId);

        if (StringUtils.isNotEmpty(keyId)) {
            personnelUseService.approve(personnelUse, dutyService.get(curDutyId), comment);
        } else {
            personnelUseService.commit(personnelUse, "com.fz.us.oa.core.entity.com.PersonnelUse", dutyService.get(curDutyId));
        }

        if(personnelUse.getProcessState().name().equals("Finished")){
            doFinished(personnelUse,parentId,nature);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId, String nature){
        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelUse personnelUse = personnelUseService.get(keyId);
        personnelUseService.approve(personnelUse, dutyService.get(curDutyId), comment);

        //归档后设置和主表的关系
        if(personnelUse.getProcessState().name().equals("Finished")){
            doFinished(personnelUse,parentId,nature);
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(PersonnelUse personnelUse,String parentId,String nature){
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        personnelInfo.setPersonnelUse(personnelUse);
        personnelInfo.setNature(Integer.parseInt(nature));
        Date now=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(now.after(DataUtil.getAfterDay(personnelUse.getContractDateEnd(),-30))){
            personnelInfo.setExpire(true);
        }else{
            personnelInfo.setExpire(false);
        }
        personnelInfoService.saveEntity(personnelInfo);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelUse personnelUse = personnelUseService.get(keyId);
            personnelUseService.back(personnelUse, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelUse personnelUse = personnelUseService.get(keyId);
            personnelUseService.deny(personnelUse, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
}
